package com.dfhc.pub.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.quickbundle.base.beans.factory.RmBeanFactory;
import org.quickbundle.base.beans.factory.RmIdFactory;
import org.quickbundle.base.web.page.RmPageVo;
import org.quickbundle.config.RmConfig;
import org.quickbundle.orgauth.IOrgauthConstants;
import org.quickbundle.orgauth.cache.RmFunctionNodeCache;
import org.quickbundle.orgauth.cache.RmPartyTypeCache;
import org.quickbundle.orgauth.rmfunctionnode.service.IRmFunctionNodeService;
import org.quickbundle.orgauth.rmfunctionnode.service.impl.RmFunctionNodeService;
import org.quickbundle.orgauth.rmfunctionnode.vo.RmFunctionNodeVo;
import org.quickbundle.orgauth.rmparty.service.IRmPartyService;
import org.quickbundle.orgauth.rmparty.util.IRmPartyConstants;
import org.quickbundle.orgauth.rmparty.vo.RmPartyVo;
import org.quickbundle.orgauth.rmpartytype.vo.RmPartyTypeVo;
import org.quickbundle.orgauth.rmrole.service.IRmRoleService;
import org.quickbundle.orgauth.rmrole.service.impl.RmRoleService;
import org.quickbundle.orgauth.rmrole.util.IRmRoleConstants;
import org.quickbundle.orgauth.rmrole.vo.RmRoleVo;
import org.quickbundle.orgauth.rmuser.service.IRmUserService;
import org.quickbundle.orgauth.rmuser.util.IRmUserConstants;
import org.quickbundle.project.IGlobalConstants;
import org.quickbundle.project.RmGlobalReference;
import org.quickbundle.project.RmProjectHelper;
import org.quickbundle.project.common.vo.RmCommonVo;
import org.quickbundle.project.login.RmUserVo;
import org.quickbundle.third.struts.RmActionHelper;
import org.quickbundle.tools.helper.RmJspHelper;
import org.quickbundle.tools.helper.RmSqlHelper;
import org.quickbundle.tools.helper.RmStringHelper;
import org.quickbundle.tools.support.tree.DeepTreeVo;
import org.quickbundle.tools.support.tree.DeepTreeXmlHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dfhc.ISystemConstant;
import com.dfhc.PjException;
import com.dfhc.pub.concurrencycontrol.RequestConcurrentRoute;
import com.dfhc.pub.service.FileDownloadService;
import com.dfhc.pub.service.FileLockService;
import com.dfhc.pub.service.FlowJsonToXmlService;
import com.dfhc.pub.service.ImageShowService;
import com.dfhc.pub.service.PubParamService;
import com.dfhc.pub.service.PubPartyService;
import com.dfhc.pub.service.SqlProcessService;
import com.dfhc.rm.user.IUserConstants;
import com.dfhc.rm.user.vo.UserVo;
import com.dfhc.util.ConvertHelper;
import com.dfhc.util.CryptoHelper;
import com.dfhc.util.CsrfHelper;
import com.dfhc.util.FileOperateHelper;
import com.dfhc.util.HttpClientUtil;
import com.dfhc.util.ImageUtil;
import com.dfhc.util.StringHelper;
import com.dfhc.util.XssHelper;
import com.dfhc.wk.frontflowdef.service.FrontFlowDefService;
import com.dfhc.wk.workflownodeconfig.service.WorkflowNodeConfigService;

//---
@Controller
@RequestMapping(value = "/pubController")
public class PubController implements IGlobalConstants {
	@Autowired
	ImageShowService imageShowService;
	@Autowired
	FileDownloadService fileDownloadService;
	@Autowired
	PubParamService pubParamService;
	@Autowired
	FlowJsonToXmlService flowJsonToXmlService;
	@Autowired
	FrontFlowDefService frontFlowDefService;
	
	
	/**
	 * 组织树公告服务
	 */
	@Autowired
	PubPartyService pubPartyService;
	@Autowired
	FileLockService fileLockService;
	@Autowired
	WorkflowNodeConfigService workflowNodeConfigService;
	@Autowired
	SqlProcessService sqlProcessService;
	@Autowired
	RmFunctionNodeService rmFunctionNodeService;
	@Autowired
	IRmRoleService roleService;
	/**
	 * 获取party
	 * 
	 * @return Service对象
	 */
	public IRmPartyService getPartyService() {
		return (IRmPartyService) RmBeanFactory
				.getBean(IRmPartyConstants.SERVICE_KEY); // 得到Service对象,受事务控制
	}

	@RequestMapping(value = "getParty")
	public String list(Model model, HttpServletRequest request) {
		String view_id = request.getParameter("view_id");
		if (view_id == null || view_id.trim().length() == 0) {
			// view_id的默认值是RM_PARTY_VIEW表的第一条记录
			List<RmCommonVo> lPartyViewId = RmProjectHelper
					.getCommonServiceInstance().doQuery(
							"SELECT ID FROM RM_PARTY_VIEW ORDER BY ID", 1, 1);
			if (lPartyViewId.size() > 0) {
				view_id = lPartyViewId.get(0).getString("id");
			} else {
				view_id = IOrgauthConstants.PartyView.DEFAULT.id();
			}
		}

		// 优先获取parent_party_code
		String parent_party_code = request.getParameter("parent_party_code");

		// 如果parent_party_code为null，获取parent_party_id且默认为""
		String parent_party_id = null;
		if (parent_party_code == null) {
			parent_party_id = request.getParameter("parent_party_id");
			if (parent_party_id == null) {
				parent_party_id = "";
			}
		}

		// 是否包含自身，默认为0。只有懒加载时有效
		boolean include_self = false;
		include_self = "1".equals(request.getParameter("include_self"));

		// 获取show_bk
		String[] aShow_bk = new String[0];
		String show_bk = request.getParameter("show_bk");
		if (show_bk != null && show_bk.trim().length() > 0) {
			String tempBk = show_bk.replaceAll("^,+", "").replaceAll(",+$", "");
			if (tempBk.trim().length() > 0) {
				aShow_bk = tempBk.trim().split(",");
			}
		}

		// 获取lazy_init，默认为1
		String lazy_init = request.getParameter("lazy_init");
		if (lazy_init == null || lazy_init.length() == 0
				|| (!"1".equals(lazy_init) && !"0".equals(lazy_init))) {
			lazy_init = "0";
		}
		// 获取允许挂接用户 add by longsebo 2016-11-14
		String is_allow_hanging_user = "";
		if (!StringHelper
				.isEmpty(request.getParameter("is_allow_hanging_user"))) {
			is_allow_hanging_user = request
					.getParameter("is_allow_hanging_user");
		}
		// 获取允许挂接角色
		String is_allow_hanging_role = "";
		if (!StringHelper
				.isEmpty(request.getParameter("is_allow_hanging_role"))) {
			is_allow_hanging_role = request
					.getParameter("is_allow_hanging_role");
		}
		// 查询树节点的sql语句
		StringBuilder sbSql = new StringBuilder();
		sbSql.append("select PR.PARENT_PARTY_ID, PR.CHILD_PARTY_ID, PR.PARENT_PARTY_CODE, PR.CHILD_PARTY_CODE, "
				+ "PR.CHILD_IS_LEAF, PR.CHILD_PARTY_NAME, P.PARTY_TYPE_ID as CHILD_PARTY_TYPE_ID, PT.ICON as CHILD_ICON, "
				+ "PT.BS_KEYWORD as CHILD_BS_KEYWORD, PR.CHILD_IS_MAIN_RELATION, PR.ORDER_CODE from RM_PARTY_RELATION PR "
				+ "join RM_PARTY P on PR.CHILD_PARTY_ID=P.ID "
				+ "join RM_PARTY_TYPE PT on P.PARTY_TYPE_ID=PT.ID where ");

		// 懒加载，只获取1层子节点
		if ("1".equals(lazy_init)) {
			// 如果parent_party_code未指定，按parent_party_id查询
			if (parent_party_code == null) {
				if ("".equals(parent_party_id)) {
					sbSql.append(" (PR.PARENT_PARTY_ID is null or PR.PARENT_PARTY_ID='')");
				} else {
					if (include_self) { // 查自身
						sbSql.append(" PR.CHILD_PARTY_ID=" + parent_party_id);
					} else { // 查父节点
						sbSql.append(" PR.PARENT_PARTY_ID=" + parent_party_id);
					}
				}
			} else { // parent_party_code不为空则按parent_party_code查询
				if ("".equals(parent_party_code)) {
					sbSql.append(" (PR.PARENT_PARTY_CODE is null or PR.PARENT_PARTY_CODE='')");
				} else {
					if (include_self) { // 查自身
						sbSql.append(" PR.CHILD_PARTY_CODE='"
								+ parent_party_code + "'");
					} else { // 查父节点
						sbSql.append(" PR.PARENT_PARTY_CODE='"
								+ parent_party_code + "'");
					}
				}
			}
			// 如果show_bk不为空，过滤
			if (aShow_bk.length > 0) {
				sbSql.append(" and PT.BS_KEYWORD in ("
						+ RmStringHelper.parseToSQLStringApos(aShow_bk) + ")");
			}
		} else {
			// 如果parent_party_code未指定，按parent_party_id查询
			if (parent_party_code == null) {
				StringBuilder sql_parentParty = new StringBuilder();
				sql_parentParty
						.append("select PR.CHILD_PARTY_CODE, PARENT_PARTY_CODE, CHILD_IS_MAIN_RELATION from RM_PARTY_RELATION PR where PR.PARTY_VIEW_ID="
								+ view_id);
				if ("".equals(parent_party_id)) {
					sql_parentParty
							.append(" and (PR.PARENT_PARTY_ID is null or PR.PARENT_PARTY_ID='')");
				} else {
					sql_parentParty.append(" and PR.PARENT_PARTY_ID="
							+ parent_party_id);
				}
				List<String> lParentPartyCode = RmProjectHelper
						.getCommonServiceInstance().query(
								sql_parentParty.toString(), new RowMapper() {
									public Object mapRow(ResultSet rs, int i)
											throws SQLException {
										return rs.getString("CHILD_PARTY_CODE");
									}
								});
				int index = 0;
				if (lParentPartyCode.size() > 0) {
					for (String parentPartyCode : lParentPartyCode) {
						if (index == 0) {
							sbSql.append(" (PR.CHILD_PARTY_CODE like '"
									+ parentPartyCode + "%'");
						} else {
							sbSql.append(" or PR.CHILD_PARTY_CODE like '"
									+ parentPartyCode + "%'");
						}
						index++;
					}
					sbSql.append(")");
				} else {
					sbSql.append(" PR.CHILD_PARTY_CODE like '" + NOT_EXIST_ID
							+ "%'");
				}
			} else {
				sbSql.append(" PR.CHILD_PARTY_CODE like '" + parent_party_code
						+ "%'");
			}
			// 如果show_bk不为空，过滤
			if (aShow_bk.length > 0) {
				sbSql.append(" and PT.BS_KEYWORD in ("
						+ RmStringHelper.parseToSQLStringApos(aShow_bk) + ")");
			}
		}
		// 增加是否允许挂接用户，角色条件 add by longsebo 2016-11-14
		if (!StringHelper.isEmpty(is_allow_hanging_user)) {
			sbSql.append("and PT.IS_ALLOW_HANGING_USER='")
					.append(is_allow_hanging_user).append("'");
		}
		if (!StringHelper.isEmpty(is_allow_hanging_role)) {
			sbSql.append("and PT.IS_ALLOW_HANGING_ROLE='")
					.append(is_allow_hanging_role).append("'");
		}
		sbSql.append(" and PR.PARTY_VIEW_ID=" + view_id);
		List<RmCommonVo> lcvo = RmProjectHelper.getCommonServiceInstance()
				.doQuery(sbSql.toString());
		model.addAttribute("beans", lcvo);
		model.addAttribute("last", lcvo.size());
		model.addAttribute("objKey", request.getParameter("objKey"));// form对应要回写的input的那么属性，第一个为要会写的id，
		model.addAttribute("fromName", request.getParameter("formName"));// from名称name属性
		model.addAttribute("view_id", view_id);// from名称name属性
		model.addAttribute("source", request.getParameter("source"));// 标志请求从哪儿来的，source=orgBack：说明是后台组织结构,
																		// source=assignDepts说明来自activiti人员分配
																		// source=orgFront说明来自前台选择组织机构
		if ("orgFront".equals(request.getParameter("source"))) {
			return "/ztree/orgFront";
		} else if ("orgBack".equals(request.getParameter("source"))) {
			return "/ztree/radioBack";
		} else if ("assignDepts".equals(request.getParameter("source"))) {
			return "/ztree/assignDepts";
		} else if ("partymanage".equals(request.getParameter("source"))) {// 受控菜单组织树管理
			return "/ztree/orgPartyTreeManage";
		} else {
			return "/ztree/radio";
		}

	}

	/**
	 * 授权菜单的组织机构树管理
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "managePartyTab")
	public String managePartyTab(HttpServletRequest request, Model model) {

		String cmd = request.getParameter("cmd");// 来自哪儿
		String view_id = request.getParameter("view_id");// 视图id
		List<RmCommonVo> lcvo = RmProjectHelper.getCommonServiceInstance()
				.doQuery("select ID, NAME from RM_PARTY_VIEW");
		Map<String, String> mpv = new HashMap<String, String>();
		for (RmCommonVo cvo : lcvo) {
			mpv.put(cvo.getString("id"), cvo.getString("name"));
			if (view_id == null) {
				view_id = cvo.getString("id");
			}
		}

		String sValue = "";
		if (IOrgauthConstants.PartyView.DEFAULT.id().equals(view_id)) {
			sValue = IOrgauthConstants.OrgTree.DEFAULT.value();
		}

		if (StringHelper.isEmpty(cmd)) {

			cmd = sValue;
		}

		model.addAttribute("cmd", cmd);
		model.addAttribute("view_id", view_id);

		this.list(model, request);// 查组织树节点数据

		model.addAttribute("child_party_code",
				request.getParameter("child_party_code"));

		return "/qb5activiti/system/managePartyTab";

	}

	@RequestMapping(value = "ajaxGetChildParty", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> ajaxGetChildParty(HttpServletRequest request,
			Model model) {

		Map<String, Object> result = new HashMap<String, Object>();

		String cmd = request.getParameter("cmd");
		String party_type = request.getParameter("party_type");

		pubPartyService.doUpdateOrgTree(cmd, party_type, request);// 操作组织树
		String view_id = request.getParameter("view_id");

		String child_party_code = request.getParameter("child_party_code");// 获取子团体编码
		RmCommonVo childPartyRelationVo = pubPartyService.queryChildRelationVo(
				view_id, child_party_code);// 根据自团体编码查询自团体的团体关心
		String child_party_id = "";// 子团体id
		if (childPartyRelationVo != null) {

			child_party_id = childPartyRelationVo.getString("child_party_id");// 获取子团体id
		}
		List<RmPartyTypeVo> listRmPartyTypeVos = pubPartyService
				.queryChildPartyType(view_id, child_party_id);
		//
		// model.addAttribute("childPartyRelationVo",
		// childPartyRelationVo);//团体关系
		// model.addAttribute("listRmPartyTypeVos", listRmPartyTypeVos);//团体类型
		result.put("listRmPartyTypeVos", listRmPartyTypeVos);
		result.put("childPartyRelationVo", childPartyRelationVo);

		return result;

	}

	/**
	 * 获取部分关联参照页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "getPartyReference")
	public String getPartyReference(HttpServletRequest request, Model model) {

		request.setAttribute(REQUEST_REFERENCE_INPUT_TYPE,
				request.getParameter(REQUEST_REFERENCE_INPUT_TYPE)); // 传送输入方式,checkbox或radio

		return "/qb5activiti/system/listPartyReference";
	}

	/**
	 * ajax 加载组织页面
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "ajaxListPartyReference")
	public void ajaxListPartyReference(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		IRmPartyService service = getPartyService();

		String queryCondition = getQueryCondition(request); // 从request中获得查询条件
		String page = request.getParameter("page") == null ? "1" : request
				.getParameter("page");
		String rows = request.getParameter("rows") == null ? ISystemConstant.DEFAULT_PAGE_SIZE
				: request.getParameter("rows");
		int rowsInt = Integer.parseInt(rows);// 页大小
		int pageInt = Integer.parseInt(page);// 当前页
		RmPageVo pageVo = RmJspHelper.transctPageVo(request,
				service.getRecordCount(queryCondition));
		pageVo.setPageSize(rowsInt);
		pageVo.setCurrentPage(pageInt);
		String orderStr = RmJspHelper.getOrderStr(request); // 得到排序信息
		List<RmPartyVo> beans = service.queryByCondition(queryCondition,
				orderStr, pageVo.getStartIndex(), pageVo.getPageSize()); // 按条件查询全部,带排序

		dataMap.put("page", pageVo.getCurrentPage());
		dataMap.put("total", pageVo.getPageCount());
		dataMap.put("records", pageVo.getRecordCount());
		dataMap.put("rows", beans);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(JSONObject.toJSONString(dataMap));

	}

	/**
	 * 团体参照查询
	 * 
	 * @param request
	 * @return
	 */
	private String getQueryCondition(HttpServletRequest request) {

		String queryCondition = "";

		List<String> lQuery = new ArrayList<String>();
		lQuery.add(RmSqlHelper.buildQueryStr(IRmPartyConstants.TABLE_NAME
				+ ".name", request.getParameter("name"),
				RmSqlHelper.TYPE_CHAR_LIKE));

		lQuery.add(RmSqlHelper.buildQueryStr(IRmPartyConstants.TABLE_NAME
				+ ".is_inherit", request.getParameter("is_inherit"),
				RmSqlHelper.TYPE_CUSTOM, "='", "'"));

		lQuery.add(RmSqlHelper.buildQueryStr(IRmPartyConstants.TABLE_NAME
				+ ".email", request.getParameter("email"),
				RmSqlHelper.TYPE_CHAR_LIKE));
		queryCondition = RmSqlHelper.appendQueryStr(lQuery
				.toArray(new String[0]));

		return queryCondition;

	}

	/**
	 * 功能菜单按钮
	 * 
	 * @param request
	 * @param orgTree
	 * @param authorityMenuTree
	 * @return
	 */
	@RequestMapping(value = "getMenuTree", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map getMenuTree(Model model, HttpServletRequest request) {
		boolean authorityMenuTree = false;
		if (request.getParameter("authorityMenuTree") == null
				&& "" == request.getParameter("authorityMenuTree")) {
			authorityMenuTree = false;
		} else {
			authorityMenuTree = Boolean.valueOf(request
					.getParameter("authorityMenuTree"));
		}

		Map<String, Object> map = new HashMap<String, Object>();
		DeepTreeXmlHandler dt = new DeepTreeXmlHandler();
		String totalCode = request.getParameter("total_code");
		String id = request.getParameter("id");
		if (totalCode == null) {
			totalCode = "";
		}
		if (!authorityMenuTree) {
			// 获取lazy_init，默认为1
			String lazy_init = request.getParameter("lazy_init");
			if (lazy_init == null || lazy_init.length() == 0
					|| (!"1".equals(lazy_init) && !"0".equals(lazy_init))) {
				lazy_init = "1";
			}
			StringBuilder sql = new StringBuilder();
			sql.append("select ID,NODE_TYPE,ENABLE_STATUS,NAME,DATA_VALUE,TOTAL_CODE,IS_LEAF,ICON from RM_FUNCTION_NODE ");
			// 启用禁用: 0=禁用,1=启用
			String enableStatus = request.getParameter("enable_status");
			// 节点类型：1=子系统、一级模块,2=子模块、功能,3=页面按钮
			String nodeType = request.getParameter("node_type");
			// 懒加载，只获取1层子节点
			if ("1".equals(lazy_init)) {
				sql.append(" WHERE ");
				if (RmStringHelper.checkNotEmpty(totalCode)) {
					sql.append("TOTAL_CODE like '" + totalCode + "%' and ");
				}

				sql.append(" ");
				sql.append(RmSqlHelper.getFunction(RmSqlHelper.Function.LENGTH,
						RmConfig.getSingleton().getDatabaseProductName()));
				sql.append("(TOTAL_CODE) = "
						+ (RmConfig.getSingleton().getDefaultTreeCodeFirst()
								.length() + totalCode.length()));
				if (RmStringHelper.checkNotEmpty(enableStatus)
						&& "1".equals(enableStatus)) {
					sql.append(" and ENABLE_STATUS='1'");
				}
				if (RmStringHelper.checkNotEmpty(nodeType)
						&& "3".equals(nodeType)) {
					sql.append(" and NODE_TYPE!='3'");
				}
				sql.append(" order by ");
				sql.append(RmSqlHelper.getFunction(RmSqlHelper.Function.SUBSTR,
						RmConfig.getSingleton().getDatabaseProductName()));
				sql.append("(TOTAL_CODE, 1, ");
				sql.append(RmSqlHelper.getFunction(RmSqlHelper.Function.LENGTH,
						RmConfig.getSingleton().getDatabaseProductName()));
				sql.append("(TOTAL_CODE)-3)");
				sql.append(", ORDER_CODE");
				// sql.append(" order by TOTAL_CODE");

				List<RmCommonVo> lcvo = RmProjectHelper
						.getCommonServiceInstance().doQuery(sql.toString());
				if (totalCode.length() < 7) {
					model.addAttribute("isParent", true);
				}
				map.put("lcvo", lcvo);
				model.addAttribute("beans", lcvo);
			} else {
				if (RmStringHelper.checkNotEmpty(enableStatus)
						&& "1".equals(enableStatus)) {
					sql.append(" where ENABLE_STATUS='1'");
				}else{
					sql.append("where  FUNCTION_PROPERTY!='3'");
				}
				sql.append(" order by TOTAL_CODE");
				List<RmCommonVo> lcvo = RmProjectHelper
						.getCommonServiceInstance().doQuery(sql.toString());
				map.put("lcvo", lcvo);
				model.addAttribute("beans", lcvo);
			}
		} else { // 从全局缓存读取菜单项
			List<String> lcvo = RmProjectHelper.getRmUserVo(request)
					.getMenuList();
			List<Object> myTrees = new ArrayList<Object>();
			// model.addAttribute("beans", lcvo);
			for (String thisCode : lcvo) {
				if (thisCode.startsWith(totalCode)) {
					RmFunctionNodeVo fnvo = RmFunctionNodeCache
							.getFunctionNode(thisCode);
					if (fnvo != null) {
						String hasChild = "1";
						DeepTreeVo dtv = new DeepTreeVo(thisCode,
								fnvo.getName(), hasChild, "");
						if (fnvo.getData_value() != null
								&& fnvo.getData_value().length() > 0) {
							// String finalHref =
							// RmUrlHelper.replaceParameter(fnvo.getData_value(),
							// request);
							String finalHref = fnvo.getData_value();
							dtv.setHrefPath(request.getContextPath()
									+ finalHref);
						}
						dtv.setTarget("contentFrame");
						if (fnvo.getIcon() != null
								&& fnvo.getIcon().startsWith("/")) {
							dtv.setLogoImagePath(request.getContextPath()
									+ fnvo.getIcon());
						}
						if (thisCode.length() == totalCode.length()
								+ RmConfig.getSingleton()
										.getDefaultTreeCodeFirst().length()) {
							dt.addTreeNode(dtv);
						} else {
							dt.addTreeNode(
									thisCode.substring(0, thisCode.length()
											- RmConfig.getSingleton()
													.getDefaultTreeCodeFirst()
													.length()), dtv);
						}
					}
					myTrees.add(fnvo);
				}
			}
			map.put("lcvo", myTrees);
		}

		return map;
	}

	/**
	 * 获取带有权限的功能菜单
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getTreeOrg")
	public String getTreeOrg(Model model, HttpServletRequest request) {
		// List list=new ArrayList();
		// IRmCommonService cs = RmProjectHelper.getCommonServiceInstance();
		List<String> codeList = RmProjectHelper.getRmUserVo(request)
				.getMenuList();
		if (codeList != null && codeList.size() > 0) {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < codeList.size(); i++) {
				if (codeList.get(i) != null && !"".equals(codeList.get(i))) {
					sb.append("'");
					sb.append(codeList.get(i));
					sb.append("'");
					if (i < codeList.size() - 1) {
						sb.append(",");
					}
				}
			}
			String sql = sqlJoinAuthorize_resource(
					RmProjectHelper.getRmUserVo(request).getParty_id_all(),
					"RM_FUNCTION_NODE",
					"RM_FUNCTION_NODE",
					"TOTAL_CODE",
					"RM_FUNCTION_NODE.ID, (select count(*) from RM_FUNCTION_NODE fn where fn.NODE_TYPE!='3' and fn.TOTAL_CODE like concat(RM_FUNCTION_NODE.TOTAL_CODE,'1%')) CHILD_COUNT, RM_FUNCTION_NODE.NODE_TYPE, RM_FUNCTION_NODE.ORDER_CODE, RM_FUNCTION_NODE.FUNCTION_PROPERTY, RM_FUNCTION_NODE.ENABLE_STATUS, RM_FUNCTION_NODE.NAME, RM_FUNCTION_NODE.DESCRIPTION, RM_FUNCTION_NODE.DATA_VALUE, RM_FUNCTION_NODE.TOTAL_CODE, RM_FUNCTION_NODE.IS_LEAF, RM_FUNCTION_NODE.ICON",
					" and RM_FUNCTION_NODE.TOTAL_CODE in ("
							+ sb.toString()
							+ ") and length(RM_FUNCTION_NODE.TOTAL_CODE)=6 and RM_FUNCTION_NODE.ENABLE_STATUS='1' and RM_FUNCTION_NODE.NODE_TYPE!='3' order by RM_FUNCTION_NODE.ORDER_CODE, SUBSTR(RM_FUNCTION_NODE.TOTAL_CODE,1,length(RM_FUNCTION_NODE.TOTAL_CODE)"
							+ ")");
			List<RmCommonVo> lvos = RmProjectHelper.getCommonServiceInstance()
					.doQuery(sql);
			model.addAttribute("lvos", lvos);
		}
		return "ztree/leftOrgZtree";

	}

	public static String sqlJoinAuthorize_resource(String[] party_ids,
			String tableName, String tableNameAlias, String joinColumnName,
			String selectStr, String whereOrderStr) {
		StringBuilder sb = new StringBuilder();
		// sb.append("select distinct(ar.OLD_RESOURCE_ID), ar.DEFAULT_ACCESS, ar.DEFAULT_IS_AFFIX_DATA, ar.DEFAULT_ACCESS_TYPE, ar.DEFAULT_IS_RECURSIVE, arr.AUTHORIZE_STATUS, arr.IS_AFFIX_DATA, arr.ACCESS_TYPE, arr.IS_RECURSIVE, ");
		sb.append("select distinct(ar.OLD_RESOURCE_ID), ");
		sb.append(selectStr);
		sb.append(" from RM_AUTHORIZE_RESOURCE ar left join RM_AUTHORIZE_RESOURCE_RECORD arr on ar.id=arr.AUTHORIZE_RESOURCE_ID join ");
		sb.append(tableName);
		sb.append(" ");
		sb.append(tableNameAlias);
		sb.append(" on ar.OLD_RESOURCE_ID=");
		sb.append(tableNameAlias);
		sb.append(".");
		sb.append(joinColumnName);
		sb.append(" where (ar.DEFAULT_ACCESS='1' or arr.PARTY_ID in(");
		sb.append(RmStringHelper.parseToSQLString(party_ids));
		sb.append(") )");
		sb.append(whereOrderStr != null ? whereOrderStr : "");
		return sb.toString();
	}

	/**
	 * 下载文件
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "download")
	public void download(Model model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String relaPath = request.getParameter(ISystemConstant.RELA_PATH);
		if (!StringHelper.isEmpty(relaPath)) {
			if (relaPath.contains("..")) {
				throw new PjException("请求路径不合法");
			}
		}
		if (!StringHelper.isEmpty(relaPath)) {
			// 构造完整的文件名路径
			String rootPath;
			rootPath = pubParamService.getRootPath();
			String fullImagePath;
			fullImagePath = rootPath + relaPath;
			fileDownloadService.download(fullImagePath, response);
		}
	}

	/**
	 * activiti 人员组织机构
	 * 
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "showAssinDetp")
	public String showAssinDetp(Model model, HttpServletRequest request) throws Exception {
		String view_id = request.getParameter("view_id");
		List<RmCommonVo> lcvo = RmProjectHelper.getCommonServiceInstance()
				.doQuery("select ID, NAME from RM_PARTY_VIEW");
		Map<String, String> mpv = new HashMap<String, String>();
		for (RmCommonVo cvo : lcvo) {
			mpv.put(cvo.getString("id"), cvo.getString("name"));
			if (view_id == null) {
				view_id = cvo.getString("id");
			}
		}

		String sValue = "";
		if (IOrgauthConstants.PartyView.DEFAULT.id().equals(view_id)) {
			sValue = IOrgauthConstants.OrgTree.DEFAULT.value();
		}

		String cmd = request.getParameter("cmd") != null ? request
				.getParameter("cmd") : sValue;
		if (view_id == null) {

			view_id = "";
		}
		return "redirect:"+CryptoHelper.encryptUrl(request,"/pubController/getParty")+"?cmd=" + cmd + "&view_id="
				+ view_id
				+ "&is_href=1&reference=1&enableCookie=true&source=assignDepts";
	}

	/**
	 * 2016/12/31根据total_code,获取该节点的下级菜单
	 * 
	 * @param model
	 * @param reques
	 * @return
	 */
	@RequestMapping(value = "getTreeOrgAjax", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String, Object> getTreeOrgAjax(Model model,
			HttpServletRequest request) {

		Map<String, Object> map = new HashMap<String, Object>();
		List<RmCommonVo> lvos = new ArrayList<RmCommonVo>();
		String total_code = request.getParameter("total_code");

		if (total_code == null || "".equals(total_code)
				|| total_code.equals("null")) {
			map.put("lvos", lvos);
			return map;
		}
		HttpSession session = RmJspHelper.getSession(request, false);
		List<RmCommonVo> child_left_true = (List<RmCommonVo>) session
				.getAttribute("child_" + total_code);// 从session中获取左侧一级菜单
		if (child_left_true != null && child_left_true.size() > 0) {// 说明session中有数据
			map.put("lvos", child_left_true);// 将父节点对应的子节点从session 中取出 放入map 返回
			return map;
		}
		List<String> codeList = RmProjectHelper.getRmUserVo(request)
				.getMenuList();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < codeList.size(); i++) {
			if (codeList.get(i) != null && !"".equals(codeList.get(i))) {
				sb.append("'");
				sb.append(codeList.get(i));
				sb.append("'");
				if (i < codeList.size() - 1) {
					sb.append(",");
				}
			}
		}

		String sql = sqlJoinAuthorize_resource(
				RmProjectHelper.getRmUserVo(request).getParty_id_all(),
				"RM_FUNCTION_NODE",
				"RM_FUNCTION_NODE",
				"TOTAL_CODE",
				"RM_FUNCTION_NODE.ID, (select count(*) from RM_FUNCTION_NODE fn where fn.NODE_TYPE!='3' and fn.TOTAL_CODE like concat(RM_FUNCTION_NODE.TOTAL_CODE,'1%')) CHILD_COUNT, RM_FUNCTION_NODE.NODE_TYPE, RM_FUNCTION_NODE.ORDER_CODE, RM_FUNCTION_NODE.FUNCTION_PROPERTY, RM_FUNCTION_NODE.ENABLE_STATUS, RM_FUNCTION_NODE.NAME, RM_FUNCTION_NODE.DESCRIPTION, RM_FUNCTION_NODE.DATA_VALUE, RM_FUNCTION_NODE.TOTAL_CODE, RM_FUNCTION_NODE.IS_LEAF, RM_FUNCTION_NODE.ICON",
				" and length(RM_FUNCTION_NODE.TOTAL_CODE)>6 and RM_FUNCTION_NODE.TOTAL_CODE like '"
						+ total_code
						+ "%'and RM_FUNCTION_NODE.TOTAL_CODE in("
						+ sb
						+ ") and RM_FUNCTION_NODE.ENABLE_STATUS='1' and RM_FUNCTION_NODE.NODE_TYPE!='3' order by SUBSTR(RM_FUNCTION_NODE.TOTAL_CODE,1,length(RM_FUNCTION_NODE.TOTAL_CODE)"
						+ "),RM_FUNCTION_NODE.ORDER_CODE");
		lvos = RmProjectHelper.getCommonServiceInstance().doQuery(sql);
		session.setAttribute("child_" + total_code, lvos);
		map.put("lvos", lvos);
		return map;
	}

	/**
	 * 2016/12/31系统后台登录后重定向该节点,查询出左侧受控树菜单，讲该一级菜单放入session 中
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "index")
	public String backLoginToIndex(Model model, HttpServletRequest request) {

		HttpSession session = RmJspHelper.getSession(request, false);
//		String rightUrl = request.getParameter(ISystemConstant.RIGHT_URL);
//		if(!StringHelper.isEmpty(rightUrl)){
//			request.setAttribute(ISystemConstant.RIGHT_URL, rightUrl);
//		}
//		String parentTotalCode = request.getParameter(ISystemConstant.PARENT_TOTALCODE);
//		if(parentTotalCode==null){
//			parentTotalCode="";
//		}
		List<RmCommonVo> sessionLeftSides = (List<RmCommonVo>) session
				.getAttribute("leftSides");// 从session中获取左侧一级菜单
//		String sessionParentTotalCode = (String) session.getAttribute(ISystemConstant.PARENT_TOTALCODE);
		if (sessionLeftSides != null && sessionLeftSides.size() > 0 ) {// 说明session中有数据,且同一个模块

			return "back/index";
		}
//		session.setAttribute(ISystemConstant.PARENT_TOTALCODE,parentTotalCode);
		List<String> codeList = RmProjectHelper.getRmUserVo(request).getMenuList();
		if (codeList != null && codeList.size() > 0) {
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < codeList.size(); i++) {
				if (codeList.get(i) != null && !"".equals(codeList.get(i))) {
					sb.append("'");
					sb.append(codeList.get(i));
					sb.append("'");
					if (i < codeList.size() - 1) {
						sb.append(",");
					}
				}
			}
			//修改length(RM_FUNCTION_NODE.TOTAL_CODE)=6 为 length(RM_FUNCTION_NODE.TOTAL_CODE)=3  条件 modify by longsebo 2017-11-07
			//修改获取下级菜单数量
			//排除公共菜单
			String whereOrderStr = " and RM_FUNCTION_NODE.TOTAL_CODE in ("
					+ sb.toString()
					+ ") and length(RM_FUNCTION_NODE.TOTAL_CODE)=6  and RM_FUNCTION_NODE.ENABLE_STATUS='1' and RM_FUNCTION_NODE.NODE_TYPE!='3' AND RM_FUNCTION_NODE.FUNCTION_PROPERTY!='3'";
			 //如果传了父级菜单码，则过滤只属于该父菜单下的菜单
//			  if(!StringHelper.isEmpty(parentTotalCode)){
//				  whereOrderStr +=" and RM_FUNCTION_NODE.TOTAL_CODE='"+parentTotalCode+"'";
//			  }
			whereOrderStr +=" order by RM_FUNCTION_NODE.ORDER_CODE";
			String sql = sqlJoinAuthorize_resource(
					RmProjectHelper.getRmUserVo(request).getParty_id_all(),
					"RM_FUNCTION_NODE",
					"RM_FUNCTION_NODE",
					"TOTAL_CODE",
					"RM_FUNCTION_NODE.ID, (select count(*) from RM_FUNCTION_NODE fn where fn.NODE_TYPE!='3' and fn.FUNCTION_PROPERTY!='3' and substr(fn.TOTAL_CODE,0,length(fn.TOTAL_CODE)-3)=RM_FUNCTION_NODE.TOTAL_CODE ) CHILD_COUNT, RM_FUNCTION_NODE.NODE_TYPE, RM_FUNCTION_NODE.ORDER_CODE, RM_FUNCTION_NODE.FUNCTION_PROPERTY, RM_FUNCTION_NODE.ENABLE_STATUS, RM_FUNCTION_NODE.NAME, RM_FUNCTION_NODE.DESCRIPTION, RM_FUNCTION_NODE.DATA_VALUE, RM_FUNCTION_NODE.TOTAL_CODE, RM_FUNCTION_NODE.IS_LEAF, RM_FUNCTION_NODE.ICON",
					whereOrderStr
							);
			List<RmCommonVo> lvos = RmProjectHelper.getCommonServiceInstance()
					.doQuery(sql);
			System.out.println(sql);
			session.setAttribute("leftSides", lvos);// 将查出的一级受控菜单放入session 中
			for(RmCommonVo  vo:lvos){
				String  total_code=vo.getString("total_code");				
				getTreeOrgAjax(model, request, total_code);
				//自动转换zkmis菜单
				//String data_value =  convertZkmisMenu(request,vo.getString("data_value"));
				//vo.put("data_value", data_value);
			}

		} else {
			List<RmCommonVo> lvos = new ArrayList<RmCommonVo>();
			session.setAttribute("leftSides", lvos);// session中没有受控菜单放入空
		}
		return "back/index";
	}

	public Map<String, Object> getTreeOrgAjax(Model model,HttpServletRequest request,String total_code) {

		Map<String, Object> map = new HashMap<String, Object>();
		List<RmCommonVo> lvos = new ArrayList<RmCommonVo>();

		
		HttpSession session = RmJspHelper.getSession(request, false);
		List<RmCommonVo> child_left_true = (List<RmCommonVo>) session.getAttribute("child_" + total_code);// 从session中获取左侧一级菜单
		if (child_left_true != null && child_left_true.size() > 0) {// 说明session中有数据
			return map;
		}
		String sql = "";
		RmUserVo rmUserVo = RmProjectHelper.getRmUserVo(request);
		//如果是普通用户
		List<String> codeList = rmUserVo.getMenuList();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < codeList.size(); i++) {
			if (codeList.get(i) != null && !"".equals(codeList.get(i))) {
				sb.append("'");
				sb.append(codeList.get(i));
				sb.append("'");
				if (i < codeList.size() - 1) {
					sb.append(",");
				}
			}
		}
		if(!ISystemConstant.DICTIONARY_RM_ADMIN_TYPE_3.equals(rmUserVo.getAdmin_type())){
		sql =sqlJoinAuthorize_resource(
				rmUserVo.getParty_id_all(),
				"RM_FUNCTION_NODE",
				"RM_FUNCTION_NODE",
				"TOTAL_CODE",
				"RM_FUNCTION_NODE.ID, (select count(*) from RM_FUNCTION_NODE fn where fn.NODE_TYPE!='3' and substr(fn.TOTAL_CODE,0,length(fn.TOTAL_CODE)-3)=RM_FUNCTION_NODE.TOTAL_CODE) CHILD_COUNT, RM_FUNCTION_NODE.NODE_TYPE, RM_FUNCTION_NODE.ORDER_CODE, RM_FUNCTION_NODE.FUNCTION_PROPERTY, RM_FUNCTION_NODE.ENABLE_STATUS, RM_FUNCTION_NODE.NAME, RM_FUNCTION_NODE.DESCRIPTION, RM_FUNCTION_NODE.DATA_VALUE, RM_FUNCTION_NODE.TOTAL_CODE, RM_FUNCTION_NODE.IS_LEAF, RM_FUNCTION_NODE.ICON",
				" and length(RM_FUNCTION_NODE.TOTAL_CODE)>6 and RM_FUNCTION_NODE.TOTAL_CODE like '"
						+ total_code
						+ "%'and RM_FUNCTION_NODE.TOTAL_CODE in("
						+ sb
						+ ") and RM_FUNCTION_NODE.ENABLE_STATUS='1' and RM_FUNCTION_NODE.NODE_TYPE!='3' AND RM_FUNCTION_NODE.FUNCTION_PROPERTY!='3' order by RM_FUNCTION_NODE.ORDER_CODE");
		}else{
		  sql="SELECT DISTINCT   (ar.OLD_RESOURCE_ID),    RM_FUNCTION_NODE.ID,   ( SELECT      COUNT(*) FROM RM_FUNCTION_NODE fn WHERE fn.NODE_TYPE!='3'   AND SUBSTR(fn.TOTAL_CODE,0,LENGTH(fn.TOTAL_CODE)-3)=RM_FUNCTION_NODE.TOTAL_CODE)"+
				 " CHILD_COUNT, RM_FUNCTION_NODE.NODE_TYPE, RM_FUNCTION_NODE.ORDER_CODE, RM_FUNCTION_NODE.FUNCTION_PROPERTY, RM_FUNCTION_NODE.ENABLE_STATUS, RM_FUNCTION_NODE.NAME,  RM_FUNCTION_NODE.DESCRIPTION,"+
				 " RM_FUNCTION_NODE.DATA_VALUE,  RM_FUNCTION_NODE.TOTAL_CODE, RM_FUNCTION_NODE.IS_LEAF,  RM_FUNCTION_NODE.ICON FROM " +
				 " RM_AUTHORIZE_RESOURCE ar LEFT JOIN    RM_AUTHORIZE_RESOURCE_RECORD arr ON    ar.id=arr.AUTHORIZE_RESOURCE_ID " +
				 "JOIN    RM_FUNCTION_NODE RM_FUNCTION_NODE ON    ar.OLD_RESOURCE_ID=RM_FUNCTION_NODE.TOTAL_CODE " +
				 " WHERE LENGTH(RM_FUNCTION_NODE.TOTAL_CODE)>6 AND  RM_FUNCTION_NODE.TOTAL_CODE like '"
						+ total_code
						+ "%'and RM_FUNCTION_NODE.TOTAL_CODE in("
						+ sb
						+ ") and RM_FUNCTION_NODE.ENABLE_STATUS='1' and RM_FUNCTION_NODE.NODE_TYPE!='3' AND RM_FUNCTION_NODE.FUNCTION_PROPERTY!='3' order by RM_FUNCTION_NODE.ORDER_CODE";	
		}
//		System.out.println("debug:"+sql);
		lvos = RmProjectHelper.getCommonServiceInstance().doQuery(sql);
		session.setAttribute("child_" + total_code, lvos);
		return map;
	}	
	/**
	 * 首页
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "welcome")
	public String welcome(Model model, HttpServletRequest request) {

		
		return "back/welcome";
	}
	
	/**
	 * 修改后台登录密码
	 */
	@RequestMapping(value = "updateSysPsd", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String, Object> updateSysPsd(Model model,
			HttpServletRequest request) {

		Map<String, Object> result = new HashMap<String, Object>();

		String old_password = request.getParameter("old_password");
		String password = request.getParameter("password");
		String password_again = request.getParameter("password_again");

		if (StringHelper.isEmpty(old_password)
				|| StringHelper.isEmpty(password)
				|| StringHelper.isEmpty(password_again)) {

			throw new PjException("密码不可为空");
		}

		if (!password_again.equals(password)) {

			throw new PjException("两次输入的新密码不一致");

		}
		// 当前登录人的用户id
		IRmUserService userService = (IRmUserService) RmBeanFactory
				.getBean(IRmUserConstants.SERVICE_KEY);
		org.quickbundle.orgauth.rmuser.vo.RmUserVo vo = userService
				.find(RmProjectHelper.getRmUserId(request));

		String uuid = vo.getAttribute2() == null ? "" : vo.getAttribute2();

		old_password = pubParamService.signRmUserPwd(uuid, old_password);// 验证旧密码

		if (!vo.getPassword().equals(old_password)) {

			throw new PjException("旧密码输入错误");
		}
		boolean success = userService.executeChangePassword(vo.getId(),
				request.getParameter("password"));
		if (!success) {
			throw new PjException("密码修改失败");

		}
		return result;

	}
	
    /**
     * 前台流程设计
     * */
    @RequestMapping(value="demo")
    public String demo(HttpServletRequest request){
  	  
  	  return "/testModeler/demo4";
    }
  
    
    
    
    /**
     * 获取菜单树
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value="getTree")
    public String getTree(Model model,HttpServletRequest request){
    	Map treeMap = getMenuTree(model, request);
  
        request.setAttribute("lcvo", treeMap.get("lcvo"));
    	
        return "/ztree/functionNodeOrgZtree";
    }
    
    /**
	 * 公共上传图片方法
	 * 
	 * @param response
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping(value="picUpload")
	public String picUpload(HttpServletResponse response,HttpServletRequest request,
			@RequestParam("appealPic") MultipartFile file, @RequestParam(value="id", required=true)String id,@RequestParam(value="billType", required=true)String billType) {
		response.setContentType("text/html; charset=utf-8");
		try {
			if (file == null || file.isEmpty()) {
				response.getWriter().write("{'message':'文件为空'}");

				return null;
			}
			BufferedImage bi = ImageIO.read(file.getInputStream());
			
			if(bi == null){
				response.getWriter().write("{'message':'上传文件不是图片！'}");
				return null;
			}
			
			if(!ImageUtil.isPicture(file.getOriginalFilename(), null)){
				response.getWriter().write("{'message':'文件后缀不对！'}");
				return null;
			}
			//图片相对路劲
			String fullPath = pubParamService.upload(file, id, request);
			
			response.getWriter().write("{'path':'" + fullPath + "', 'fileName':'" + fullPath.substring(fullPath.lastIndexOf(File.separator) + 1) + "'}");
			return null;
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			response.getWriter().write("{'message':'上传失败,请重新上传'}");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
    /**
	 * 获取布局模板内容
	 *
	 */
    @RequestMapping(value = "getLayoutTemp")
    public String getTemplate(HttpServletRequest request,HttpServletResponse response)  {
    	String url = request.getParameter(ISystemConstant.PREDEFINED_JSP_URL);
    	return url;
    }
    /**
	 * 显示图片
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "showImg")
	public void showImg(Model model, HttpServletRequest request,HttpServletResponse response) throws Exception {
		String relaPath = request.getParameter(ISystemConstant.RELA_PATH);
		
		if(!StringHelper.isEmpty(relaPath)){
			//构造完整的图片路径
			String rootPath;
			rootPath = pubParamService.getRootPath();
			String fullImagePath;			
			fullImagePath = rootPath+relaPath;							
			imageShowService.show(fullImagePath, response);
		}
	}
	/**
	 * 获取编码表的值
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getRmCodeData/{codeType}/{dataKey}",  produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getRmCodeData(@PathVariable("codeType") String codeType,@PathVariable("dataKey") String dataKey,HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		
		if(StringHelper.isEmpty(codeType)||StringHelper.isEmpty(dataKey)){
			result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			result.put(ISystemConstant.AJAX_MESSAGE, "缺少参数!");
		}else{
			String dataValue = RmGlobalReference.get(codeType, dataKey);
			result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
			result.put(ISystemConstant.AJAX_MESSAGE, "操作成功!");
			result.put(ISystemConstant.AJAX_BEAN,dataValue );
		}
		return result;
	}
	/**
	 * 获取指定表的id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getNewId/{tableName}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> getNewId(@PathVariable("tableName") String tableName,HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		
		if(StringHelper.isEmpty(tableName)){
			result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			result.put(ISystemConstant.AJAX_MESSAGE, "缺少表名参数!");
		}else{
			String id = RmIdFactory.requestId(tableName);
			result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
			result.put(ISystemConstant.AJAX_MESSAGE, "操作成功!");
			result.put(REQUEST_ID,id);
		}
		return result;
	}
    /**
	 * 打开页面
	 *
	 */
    @RequestMapping(value = "openJsp")
    public String openJsp(HttpServletRequest request,HttpServletResponse response)  {
    	String url = request.getParameter(ISystemConstant.PREDEFINED_JSP_URL);
    	//循环将所有参数，放到request attribute
    	Map<String, Object> map = ConvertHelper.toMap(request.getParameterMap());
    	if(map!=null){
	    	Set<String> keyset = map.keySet();
	    	for(String key:keyset){
	    		request.setAttribute(key, map.get(key));
	    	}
    	}
    	return url;
    }
    /**
	 * 代理转发 get 模式 reset api,避免跨域问题 
	 * @remark 为了避免参数混乱，所有参数严禁拼接到url后面，应该通过ajax data传递过来
	 * @throws IOException 
	 */
	@RequestMapping(value="proxyGetResetApi")
	public void proxyGetResetApi(HttpServletRequest request,HttpServletResponse response) throws IOException{
		HashMap<String, String> hashMap = new HashMap<String, String>();
		String url;		
		String host;
		
		//获取请求url
		url = request.getParameter(ISystemConstant.URL);
		if(StringHelper.isEmpty(url)){
			throw new PjException("缺少url参数");
		}
		//截取"//"到"/"之间字符
		int spos;
		int epos;
		spos = StringHelper.findInStr(0, url, "//");
		if(spos==-1){
			spos=0;
		}
		//优先查找冒号,找不到再找/
		epos = StringHelper.findInStr(spos+2, url, ":");
		if(epos==-1){
			epos = StringHelper.findInStr(spos+2, url, "/");
			if(epos==-1){
				epos = url.length();
			}
		}
		host = url.substring(spos+2, epos);
		hashMap.put("Host", host);
		hashMap.put("User-Agent",
				"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
		hashMap.put("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		hashMap.put("Accept-Encoding", "gzip, deflate");
		hashMap.put("Accept-Language",
				"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
		hashMap.put("Connection", "keep-alive");
		hashMap.put("Referer", url);
		hashMap.put("Cookie", "JSESSIONID="+request.getSession(false).getId());
		
		String info="";
		try {			
			info = HttpClientUtil.get(url,hashMap,ConvertHelper.toMap(request.getParameterMap()));
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}		
		response.setCharacterEncoding(ISystemConstant.ENCODE_UTF_8);
		response.getWriter().write(info);
	}
    /**
	 * 代理转发post 模式 reset api,避免跨域问题  支持文件传送 
	 * @throws IOException 
	 */
	@RequestMapping(value="proxyPostResetApi")
	public void proxyPostResetApi(HttpServletRequest request,HttpServletResponse response) throws IOException{
		HashMap<String, String> hashMap = new HashMap<String, String>();
		String url;		
		String host;
		try{
			//获取请求url
			url = request.getParameter(ISystemConstant.URL);
			if(StringHelper.isEmpty(url)){
				throw new PjException("缺少url参数");
			}
			//截取"//"到"/"之间字符
			int spos;
			int epos;
			spos = StringHelper.findInStr(0, url, "//");
			if(spos==-1){
				spos=0;
			}
			//优先查找冒号,找不到再找/
			epos = StringHelper.findInStr(spos+2, url, ":");
			if(epos==-1){
				epos = StringHelper.findInStr(spos+2, url, "/");
				if(epos==-1){
					epos = url.length();
				}
			}
			host = url.substring(spos+2, epos);
			hashMap.put("Host", host);
			hashMap.put("User-Agent",
					"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
			hashMap.put("Accept",
					"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			hashMap.put("Accept-Encoding", "gzip, deflate");
			hashMap.put("Accept-Language",
					"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			hashMap.put("Connection", "keep-alive");
			hashMap.put("Referer", url);
			hashMap.put("Cookie", "JSESSIONID="+request.getSession(false).getId());
			
			String info="";
						
			Map<String, InputStream> inStreamMap = new HashMap<String,InputStream>();
			List<MultipartFile> files = FileOperateHelper.listMultipartFile(request);
			if(files!=null){
				for(int i=0;i<files.size();i++){
					inStreamMap.put(ConvertHelper.toString(i), files.get(i).getInputStream());
				}
			}
			info = HttpClientUtil.postInStream(url, ConvertHelper.toMap(request.getParameterMap()), hashMap, inStreamMap);
			
			//将info还原为map,后返回csrf随机码
			Map<String,Object> orgMap = null;
			
			orgMap = JSON.parseObject(info, Map.class);
			//返回最新的csrf随机码
			orgMap.put(ISystemConstant.CSRF_CODE, CsrfHelper.getCsrfCode(request));
			response.setCharacterEncoding(ISystemConstant.ENCODE_UTF_8);
			response.getWriter().write(JSON.toJSONString(orgMap));
		}catch(Throwable e){
			Map<String,Object> result = new HashMap<String,Object>();
			if(e instanceof PjException){
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
			}else{
				result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				result.put(ISystemConstant.AJAX_MESSAGE, "操作失败!");
			}
			//返回最新的csrf随机码
			result.put(ISystemConstant.CSRF_CODE, CsrfHelper.getCsrfCode(request));
			response.setCharacterEncoding(ISystemConstant.ENCODE_UTF_8);
			response.getWriter().write(JSON.toJSONString(result));
		}
	}
	/**
	 * ajax懒加载模式获取组织树  支持参数有：
	 *  视图id：view_id
	 *  是否允许挂接用户:is_allow_hanging_user
	 *  是否允许挂接角色:is_allow_hanging_role
	 *  父级编码：parent_party_code
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "ajaxGetParty", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> ajaxGetParty(HttpServletRequest request) {
		//获取视图ID
		String view_id = request.getParameter("view_id");
		if (view_id == null || view_id.trim().length() == 0) {
			// view_id的默认值是RM_PARTY_VIEW表的第一条记录
			List<RmCommonVo> lPartyViewId = RmProjectHelper
					.getCommonServiceInstance().doQuery(
							"SELECT ID FROM RM_PARTY_VIEW ORDER BY ID", 1, 1);
			if (lPartyViewId.size() > 0) {
				view_id = lPartyViewId.get(0).getString("id");
			} else {
				view_id = IOrgauthConstants.PartyView.DEFAULT.id();
			}
		}
		Map<String, Object> result = new HashMap<String, Object>();
		//父级编码	为空时默认为A
		String parent_party_code = request.getParameter("child_party_code");
		if(StringHelper.isEmpty(parent_party_code)){
			parent_party_code = ISystemConstant.ORG_TREE_TOP_CODE;
		}
		// 获取允许挂接用户 add by longsebo 2016-11-14
		String is_allow_hanging_user = "";
		if (!StringHelper
				.isEmpty(request.getParameter("is_allow_hanging_user"))) {
			is_allow_hanging_user = request
					.getParameter("is_allow_hanging_user");
		}
		// 获取允许挂接角色
		String is_allow_hanging_role = "";
		if (!StringHelper
				.isEmpty(request.getParameter("is_allow_hanging_role"))) {
			is_allow_hanging_role = request
					.getParameter("is_allow_hanging_role");
		}

		StringBuilder sbSql = new StringBuilder();
		sbSql.append("select PR.PARENT_PARTY_ID, PR.CHILD_PARTY_ID, PR.PARENT_PARTY_CODE, PR.CHILD_PARTY_CODE, ")
				.append("PR.CHILD_IS_LEAF as is_leaf, PR.CHILD_PARTY_NAME as name, P.PARTY_TYPE_ID as CHILD_PARTY_TYPE_ID, PT.ICON as CHILD_ICON, ")
				.append("PT.BS_KEYWORD as CHILD_BS_KEYWORD, PR.CHILD_IS_MAIN_RELATION, PR.ORDER_CODE from RM_PARTY_RELATION PR ")
				.append("join RM_PARTY P on PR.CHILD_PARTY_ID=P.ID ")
				.append("join RM_PARTY_TYPE PT on P.PARTY_TYPE_ID=PT.ID where ")
				.append(" PR.PARTY_VIEW_ID='").append(view_id).append("'")
		        .append(" and PR.PARENT_PARTY_CODE='").append(parent_party_code).append("'");
		// 增加是否允许挂接用户，角色条件 add by longsebo 2016-11-14
		if (!StringHelper.isEmpty(is_allow_hanging_user)) {
			sbSql.append("and PT.IS_ALLOW_HANGING_USER='")
					.append(is_allow_hanging_user).append("'");
		}
		if (!StringHelper.isEmpty(is_allow_hanging_role)) {
			sbSql.append("and PT.IS_ALLOW_HANGING_ROLE='")
					.append(is_allow_hanging_role).append("'");
		}		
		List<RmCommonVo> lcvo = RmProjectHelper.getCommonServiceInstance()
				.doQuery(sbSql.toString());
		result.put("trees", lcvo);
		return result;

	}
    /**
     * 跳转到执行sql页面
     *
     */
    @RequestMapping(value="execsqlpage")
    public String execsql(HttpServletRequest request){  	  
  	  return "/dbmaintenance/execusql";
    }
    /**
     * 执行上传sql文件
     *
     */
    @RequestMapping(value="doExecsqlpage")
    public void doexecsql(HttpServletRequest request, HttpServletResponse response){
        boolean bLock = false;
        try{
	   	   bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
		   //获取上传文件sql
		   List<MultipartFile> uploadFiles = FileOperateHelper.listMultipartFile(request);
		   if(uploadFiles==null ||uploadFiles.isEmpty()){
				throw new PjException("缺少上传文件!");
		   }
		   sqlProcessService.doExecsql(uploadFiles.get(0));
		   Map<String, Object> result = new HashMap<String, Object>();
		   result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
		   result.put(ISystemConstant.AJAX_MESSAGE, "执行成功!");		    
		   try {
			   responseObjectJson(result,response);
		   } catch (IOException e) {
			   e.printStackTrace();
		   }		   
        } catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();//
			result.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);			
			//result.put(ISystemConstant.AJAX_MESSAGE, e.getMessage());
			result.put(ISystemConstant.AJAX_MESSAGE, "执行sql失败!");
			try {
				responseObjectJson(result,response);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}  
			
			return;
        }finally{
 		   //最后解锁
 		   RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID),bLock);
         }
        
    }
    /**
     * 执行自定义sql查询
     */
    @RequestMapping(value = "doCustomQuery", produces = "application/json")
	@ResponseBody
	public Map<String, Object> doCustomQuery(Model model, HttpServletRequest request) throws Exception {
		String sql = (String)request.getSession().getAttribute(ISystemConstant.DICTIONARY_SQL);
		//request.setAttribute("sql", sql);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if(StringHelper.isEmpty(sql)){
			dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			dataMap.put(ISystemConstant.AJAX_MESSAGE, "缺少sql");
			return dataMap;
		}
		boolean bLock = false;
		

		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));

			String page = request.getParameter("page") == null ? "1" : request.getParameter("page");
			String rows = request.getParameter("rows") == null ? ISystemConstant.DEFAULT_PAGE_SIZE : request.getParameter("rows");
			int rowsInt = Integer.parseInt(rows);// 页大小
			int pageInt = Integer.parseInt(page);// 当前页
			if (!StringHelper.isEmpty(sql)) {
				// 为了绕开sql注入检查，将query替换为select
				sql = StringHelper.replaceAllIgnoreCase(sql, "query", "select");
				String sqlCount = "select count(*) from (" + sql + ") t";

				int totalNum = RmProjectHelper.getCommonServiceInstance().doQueryForInt(sqlCount);
				RmPageVo pageVo = RmJspHelper.transctPageVo(request, totalNum);
				pageVo.setPageSize(rowsInt);

				List<RmCommonVo> maps = RmProjectHelper.getCommonServiceInstance().doQuery(sql, pageInt, rowsInt);
				dataMap.put("page", pageInt);
				dataMap.put("total", pageVo.getPageCount());
				dataMap.put("records", totalNum);
				dataMap.put("rows", maps);
				dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
			} else {
				dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				dataMap.put(ISystemConstant.AJAX_MESSAGE, "缺少sql");
			}
			return dataMap;
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
			return dataMap;
		} finally {
			// 最后解锁
			RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
		}

	}
    /**
     * 自定义sql录入界面
     */
    @RequestMapping(value = "customquery", method = RequestMethod.GET)
    public String customquery(Model model,HttpServletRequest request) throws Exception {
    	return "/qb5activiti/rm/customquery/list";
    }    
    /**
     * 获取自定义sql列名查询
     */
    @RequestMapping(value = "getCustomqueryFieldNames", produces="application/json")
    @ResponseBody
    public Map<String,Object> getCustomqueryFieldNames(HttpServletRequest request) throws Exception {
    	String sql = (String)request.getSession().getAttribute(ISystemConstant.DICTIONARY_SQL);
    	/*String sql = request.getParameter("sql");
    	request.setAttribute("sql", sql);*/
    	Map<String, Object> dataMap = new HashMap<String, Object>();
		if(StringHelper.isEmpty(sql)){
			dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			dataMap.put(ISystemConstant.AJAX_MESSAGE, "缺少sql");
			return dataMap;
		}
		boolean bLock = false;
		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));

			if (!StringHelper.isEmpty(sql)) {
				// 为了绕开sql注入检查，将query替换为select
				sql = StringHelper.replaceAllIgnoreCase(sql, "query", "select");

				List<RmCommonVo> maps = RmProjectHelper.getCommonServiceInstance().doQuery(sql, 1, 1);
				List<Map<String, Object>> columnDefines = new ArrayList<Map<String, Object>>();
				if (maps != null && maps.size() > 0) {
					RmCommonVo vo = maps.get(0);
					Iterator it = vo.keySet().iterator();
					while (it.hasNext()) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("data", it.next().toString());
						columnDefines.add(map);
					}
					dataMap.put("columnNames", columnDefines);
				} else {
					dataMap.put("columnNames", "");
				}
				dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
			} else {
				dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
				dataMap.put(ISystemConstant.AJAX_MESSAGE, "缺少sql");
			}

			return dataMap;
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
			return dataMap;
		} finally {
			// 最后解锁
			RequestConcurrentRoute.getSingleton().unLock(request.getParameter(ISystemConstant.JSGUID), bLock);
		}
    }
    
	/**
	 * 获取权限树
	 * 
	 * @param request
	 * @param orgTree
	 * @param authorityMenuTree
	 * @return
	 */
	@RequestMapping(value = "getAuthorityTree", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public String getAuthorityTree(Model model, HttpServletRequest request) {
		// 1.获取父total_code
		String id = request.getParameter("id"); //角色ID
//		RmRoleService rService = (RmRoleService)RmBeanFactory.getBean(IRmRoleConstants.SERVICE_KEY);
//		RmRoleVo rvo =  rService.find(id);
//		String partyTypeName = RmPartyTypeCache.getPartyType(IRmRoleConstants.TABLE_NAME).getName();
		//取出已经赋给的功能菜单权限
		String old_code_id = "";
		List<RmCommonVo> authorizeResourceListId = RmProjectHelper.getCommonServiceInstance().doQuery("SELECT AR.OLD_RESOURCE_ID  FROM RM_AUTHORIZE_RESOURCE_RECORD ARR JOIN RM_AUTHORIZE_RESOURCE AR ON ARR.AUTHORIZE_RESOURCE_ID=AR.ID WHERE ARR.PARTY_ID="+id);
		for(RmCommonVo vo :authorizeResourceListId){
			old_code_id += vo.get("old_resource_id")+",";
		}
		if(old_code_id!=null&&!old_code_id.equals("")){
			old_code_id = old_code_id.substring(0,old_code_id.length()-1);
		}
		System.out.println(old_code_id);
		String[]  oldCodeIdArray= old_code_id.split(",");

		// 2.创建zNodes,用于拼接zTree所需要的数据
		String zNodes = "";
		zNodes += "[";
		// 获取菜单集合
		List<RmFunctionNodeVo> rmFunctionNodeVoList = rmFunctionNodeService.queryByCondition(null, null);
		// 遍历菜单集合,进行zTree节点数据的拼接
		for (RmFunctionNodeVo rmFunctionNodeVo : rmFunctionNodeVoList) {
			// 根据total_code的规律,判断父节点以及子节点
			String total_code = rmFunctionNodeVo.getTotal_code();
			//获取name
			String name = rmFunctionNodeVo.getName();
			// 一级菜单
			if(total_code.length()==3){
				boolean flag = false;
				for (String oldCode : oldCodeIdArray) {
					if(total_code.equals(oldCode)){
						flag = true;
					}
				}
				if(flag){
					zNodes += "{id:\""+total_code+"\",pId:0,name:\""+name+"\", open:true,checked:true},";
				}else{
					zNodes += "{id:\""+total_code+"\",pId:0,name:\""+name+"\", open:true},";
				}
			}
			// 二级菜单
			if(total_code.length()==6){
				// 根据total_code截取出父id
				String pid = total_code.substring(0, 3);
				boolean flag = false;
				for (String oldCode : oldCodeIdArray) {
					if(total_code.equals(oldCode)){
						flag = true;
					}
				}
				if(flag){
					zNodes += "{id:\""+total_code+"\",pId:0,name:\""+name+"\", open:true,checked:true},";
				}else{
					zNodes += "{id:\""+total_code+"\",pId:0,name:\""+name+"\", open:true},";
				}
			}
			// 三级菜单
			if(total_code.length()==9){
				// 根据total_code截取出父id
				String pid = total_code.substring(0, 6);
				boolean flag = false;
				for (String oldCode : oldCodeIdArray) {
					if(total_code.equals(oldCode)){
						flag = true;
					}
				}
				if(flag){
					zNodes += "{id:\""+total_code+"\",pId:0,name:\""+name+"\", open:true,checked:true},";
				}else{
					zNodes += "{id:\""+total_code+"\",pId:0,name:\""+name+"\", open:true},";
				}
			}
		}
		//zNodes.substring(0,zNodes.length());
		zNodes += "]";
		System.out.println(zNodes);
		return zNodes;
	}
	
	/**
     * 跳转到编辑和查看页面
     * @param model 模型
     * @param request http请求对象
     * @return 跳转的列表jsp     
     */
    @RequestMapping(value = "showAuthorizationPage")
    public String showPage(Model model, HttpServletRequest request) {
    	//获取id
    	String treeId = request.getParameter("treeId");
    	model.addAttribute("treeId", treeId);
        return "/qb5activiti/rm/rmrole/authorization";
    }
    
    /**
	 * 保存角色授权
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "updateRoleFunctionNode")
	public String updateRoleFunctionNode(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String role_id = request.getParameter("role_id");
		String function_node_code = request.getParameter("function_node_ids");
		System.err.println(function_node_code);
		String[] values = function_node_code.split(",");
		List<String> list = new ArrayList<>();
		for (int i = 0; i < values.length; i++) {
			RmFunctionNodeVo rmFunctionNodeVo = rmFunctionNodeService.findByTotalCodePrecision(values[i]);
			if(rmFunctionNodeVo.getIs_leaf().equals("1")){
				List<RmFunctionNodeVo> rmFunctionNodeVos = rmFunctionNodeService.findByLeafAndTotalCode(values[i]+"%");
				if(rmFunctionNodeVos!=null && rmFunctionNodeVos.size()>0){
					for (int j = 0; j < rmFunctionNodeVos.size(); j++) {
						list.add(rmFunctionNodeVos.get(j).getTotal_code());
					}
				}
			}
		}
		for (int i = 0; i < list.size(); i++) {
			function_node_code = function_node_code + "," + list.get(i);
		}
		System.err.println(function_node_code);
		// 重新添加授权记录和授权资源
		String[] nodeCode = RmStringHelper.parseToArray(function_node_code);
		String[] nodeCode_name = RmStringHelper.parseToArray(request
				.getParameter("function_node_id_names"));
		if (nodeCode != null && role_id != null
				&& (nodeCode.length > 0 || role_id.trim().length() > 0)) {
			List<RmFunctionNodeVo> lvo = new ArrayList<RmFunctionNodeVo>();
			for (int i = 0; i < nodeCode.length; i++) {
				RmFunctionNodeVo vo = new RmFunctionNodeVo();
				vo.setTotal_code(nodeCode[i]);
				if (nodeCode_name.length >= i + 1) {
					vo.setName(nodeCode_name[i]);
				}
				lvo.add(vo);
			}
			roleService.insertPartyResource(
					lvo.toArray(new RmFunctionNodeVo[0]), role_id);
		}
		return "成功";
	}
    /**
     * map转换为json,输出到response
     * @param result
     * @param response
     * @throws IOException 
     */
	private void responseObjectJson(Map<String, Object> result,
			HttpServletResponse response) throws IOException {
		response.setHeader("Content-type","text/html;charset=UTF-8");  
    	response.getWriter().print(JSON.toJSONString(result));
    	response.getWriter().flush();
    	response.getWriter().close();
	}
	
	/**
     * 执行上传sql文件
     * @return 
     * @throws IOException 
     *
     */
	@RequestMapping(value = "doQuerysqlpage")
	public void doQuerysqlpage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		boolean bLock = false;
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			bLock = RequestConcurrentRoute.getSingleton().lock(request.getParameter(ISystemConstant.JSGUID));
			String sql = "";
			// 获取上传文件sql
			List<MultipartFile> uploadFiles = FileOperateHelper.listMultipartFile(request);
			if (uploadFiles == null || uploadFiles.isEmpty()) {
				if (request.getSession() != null) {
					sql = (String) request.getSession().getAttribute(ISystemConstant.DICTIONARY_SQL);
					if (StringHelper.isEmpty(sql)){
						throw new PjException("缺少上传文件!");
					}
				} else{
					throw new PjException("请重新登录!");
				}
			} else {
				sql = new String(uploadFiles.get(0).getBytes(), ISystemConstant.ENCODE_UTF_8);
				request.getSession().setAttribute(ISystemConstant.DICTIONARY_SQL, sql);
			}

			dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_SUCCESS);
			dataMap.put(ISystemConstant.AJAX_MESSAGE, "执行成功");

			responseObjectJson(dataMap, response);
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put(ISystemConstant.AJAX_STATUS, ISystemConstant.AJAX_RESULT_FAIL);
			dataMap.put(ISystemConstant.AJAX_MESSAGE, "查询失败!");
			responseObjectJson(dataMap, response);
			return;
		}

	}
   
}
